const ajax = {
    // Helper function to convert query params to URL string
    buildQueryParams: (params) => {
        return Object.keys(params)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
            .join('&');
    },

    handleResponse: (xhr, resolve, reject) => {
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        resolve(response);
                    } catch (error) {
                        reject(`JSON解析错误: ${error}`);
                    }
                } else {
                    reject(`请求失败，状态码: ${xhr.status}`);
                }
            }
        };

        xhr.onerror = function () {
            reject("网络错误");
        };
    },

    get: (url, params = {}) => {
        return new Promise((resolve, reject) => {
            const queryString = ajax.buildQueryParams(params);
            const fullUrl = queryString ? `${url}?${queryString}` : url;

            const xhr = new XMLHttpRequest();
            xhr.open('GET', fullUrl, true);

            ajax.handleResponse(xhr, resolve, reject);

            xhr.send();
        });
    },

    post: (url, data = {}, params = {}) => {
        return new Promise((resolve, reject) => {
            const queryString = ajax.buildQueryParams(params);
            const fullUrl = queryString ? `${url}?${queryString}` : url;

            const xhr = new XMLHttpRequest();
            xhr.open('POST', fullUrl, true);
            xhr.setRequestHeader('Content-Type', 'application/json');

            ajax.handleResponse(xhr, resolve, reject);

            xhr.send(JSON.stringify(data));
        });
    },

    put: (url, data = {}, params = {}) => {
        return new Promise((resolve, reject) => {
            const queryString = ajax.buildQueryParams(params);
            const fullUrl = queryString ? `${url}?${queryString}` : url;

            const xhr = new XMLHttpRequest();
            xhr.open('PUT', fullUrl, true);
            xhr.setRequestHeader('Content-Type', 'application/json');

            ajax.handleResponse(xhr, resolve, reject);

            xhr.send(JSON.stringify(data));
        });
    },

    delete: (url, params = {}) => {
        return new Promise((resolve, reject) => {
            const queryString = ajax.buildQueryParams(params);
            const fullUrl = queryString ? `${url}?${queryString}` : url;

            const xhr = new XMLHttpRequest();
            xhr.open('DELETE', fullUrl, true);

            ajax.handleResponse(xhr, resolve, reject);

            xhr.send();
        });
    }
};


//防抖函数
function debounce(fn, delay) {
    let timeout;
    return function (...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => fn.apply(context, args), delay);
    }
}

const clearInput = (inputId) => {
    const inputField = document.getElementById(inputId);
    if (inputField) {
        inputField.value = '';
        inputField.dispatchEvent(new Event('input'));
    }
}

const useInput = (inputId) => {
    return new Promise((resolve, reject) => {
        const inputElement = document.querySelector(inputId);
        if (!inputElement) {
            reject(new Error('Input element not found'));
            return;
        }

        inputElement.addEventListener('input', debounce((e) => {
            if (e.target.tagName.toLowerCase() === 'input') {
                resolve(e.target.value);
            }
        }, 500));
    });
};

// 弹出框
const modal = (()=>{
    // 创建全局弹出框的样式和结构
    const modalStyle = `
    .modal {
        display: none; /* 默认隐藏 */
        position: fixed; /* 固定定位 */
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
        justify-content: center; /* 垂直和水平居中 */
        align-items: center; /* 垂直和水平居中 */
        z-index: 1000; /* 确保弹出框在最上层 */
    }
    .modal-content {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        text-align: center; /* 文本居中 */
    }
    .close-btn {
        margin-top: 10px;
        padding: 10px 15px;
        border: none;
        background-color: #007BFF;
        color: white;
        border-radius: 5px;
        cursor: pointer;
    }
    .close-btn:hover {
        background-color: #0056b3;
    }
`;

// 动态添加 CSS 样式
    const styleSheet = document.createElement("style");
    styleSheet.type = "text/css";
    styleSheet.innerText = modalStyle;
    document.head.appendChild(styleSheet);

// 创建弹出框的结构
    const modalHTML = `
    <div class="modal" id="modal">
        <div class="modal-content">
            <p id="modalMessage">这是一个弹出框！</p>
            <button class="close-btn" id="closeModalBtn">关闭</button>
        </div>
    </div>
`;

// 动态添加弹出框到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);

// 显示弹出框的函数
    function showModal(message) {
        const modal = document.getElementById('modal');
        const modalMessage = document.getElementById('modalMessage');
        modalMessage.textContent = message; // 设置弹出框的提示信息
        modal.style.display = 'flex'; // 显示弹出框
    }

// 关闭弹出框的函数
    function closeModal() {
        const modal = document.getElementById('modal');
        modal.style.display = 'none'; // 隐藏弹出框
    }

// 绑定按钮事件
// document.getElementById('showModalBtn').addEventListener('click', () => {
//     showModal('请求信息提示：操作成功！');
// });

    document.getElementById('closeModalBtn').addEventListener('click', closeModal);

// 点击弹出框外部区域关闭弹出框
    document.getElementById('modal').addEventListener('click', (event) => {
        if (event.target === document.getElementById('modal')) {
            closeModal();
        }
    });
    return showModal
})()